package com.chengh.nami.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengh.nami.common.enums.system.DeptStatusEnum;
import com.chengh.nami.common.exception.BizException;
import com.chengh.nami.common.response.TreeSelect;
import com.chengh.nami.common.utils.StringUtils;
import com.chengh.nami.system.mapper.SysDeptMapper;
import com.chengh.nami.system.pojo.SysDept;
import com.chengh.nami.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门实现列表
 *
 * @author chengh
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    @Override
    public List<SysDept> getDeptList(SysDept sysDept) {
        return baseMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .like(StringUtils.isNotEmpty(sysDept.getDeptName()), SysDept::getDeptName, sysDept.getDeptName())
                .eq(StringUtils.isNotEmpty(sysDept.getStatus()), SysDept::getStatus, sysDept.getStatus())
                .orderByAsc(SysDept::getOrderNum));
    }

    @Override
    public boolean addSysDept(SysDept sysDept) {
        validDeptNam(sysDept);
        return this.save(sysDept);
    }

    @Override
    public boolean updateSysDept(SysDept sysDept) {
        validDeptNam(sysDept);
        return this.updateById(sysDept);
    }

    @Override
    public boolean delDept(Long id) {
        // TODO 需要判断该部门下是否存在用户
        // 需要判断该部门是否有子部门
        List<SysDept> list = this.list(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, id));
        if (!CollectionUtils.isEmpty(list)) {
            throw new BizException("存在子部门，不允许删除！");
        }
        return this.removeById(id);
    }

    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<SysDept>().eq(dept.getParentId() != null, SysDept::getParentId, dept.getParentId())
                .eq(dept.getId() != null, SysDept::getId, dept.getId())
                .eq(SysDept::getStatus, DeptStatusEnum.NORMAL.getCode())
                .like(StringUtils.isNotEmpty(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName());
        return buildDeptTreeSelect(this.list(queryWrapper));
    }

    private List<TreeSelect> buildDeptTreeSelect(List<SysDept> sysDepts) {
        ArrayList<TreeSelect> treeSelects = new ArrayList<>();
        for (SysDept sysDept : sysDepts) {
            // 找到根节点进行处理，找下一级节点
            if(0 == sysDept.getParentId()) {
                treeSelects.add(findChildren(sysDept,sysDepts));
            }
        }
        return treeSelects;
    }

    /**
     * 递归构建树对象
     * @param sysDept 根节点
     * @param sysDepts 所有节点
     * @return TreeSelect
     */
    private TreeSelect findChildren(SysDept sysDept, List<SysDept> sysDepts) {
        TreeSelect treeSelect = new TreeSelect();
        treeSelect.setId(sysDept.getId());
        treeSelect.setLabel(sysDept.getDeptName());
        for (SysDept dept : sysDepts) {
            if(sysDept.getId().equals(dept.getParentId())) {
                if(treeSelect.getChildren() == null){
                    treeSelect.setChildren(new ArrayList<>());
                }
                // 把这个节点menu作为新的根节点继续向下构造树,再把构造的结果作为rootMenu的子节点
                treeSelect.getChildren().add(findChildren(dept,sysDepts));
            }
        }
        return treeSelect;
    }


    /**
     * 更新和修改时校验同名
     *
     * @param sysDept 部门信息
     */
    private void validDeptNam(SysDept sysDept) {
        Long parentId = sysDept.getParentId();
        List<SysDept> sysDepts = this.list(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, parentId));
        if (!CollectionUtils.isEmpty(sysDepts)) {
            List<SysDept> collect = sysDepts.stream().filter(item -> item.getDeptName().equals(sysDept.getDeptName()) && !item.getId().equals(sysDept.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                throw new BizException("同层级下有部门名称重复");
            }
        }
    }

}
